package com.ruoyi.web.controller.data;

import com.ruoyi.base.domain.BaseGood;
import com.ruoyi.base.domain.BaseLimit;
import com.ruoyi.base.service.IBaseGoodService;
import com.ruoyi.base.service.IBaseLimitService;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.enums.SystemType;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.data.domain.DataInventory;
import com.ruoyi.data.domain.DataInventoryRecord;
import com.ruoyi.data.service.IDataInventoryRecordService;
import com.ruoyi.data.service.IDataInventoryService;
import com.ruoyi.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * 库存记录Controller
 *
 * @author ruoyi
 * @date 2022-10-03
 */
@RestController
@RequestMapping("/data/inventoryRecord")
public class DataInventoryRecordController extends BaseController {

    @Autowired
    private IDataInventoryService dataInventoryService;

    @Autowired
    private IDataInventoryRecordService dataInventoryRecordService;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private IBaseGoodService goodService;

    @Autowired
    private IBaseLimitService limitService;

    /**
     * 查询库存记录列表
     */
    @PreAuthorize("@ss.hasPermi('data:inventoryRecord:list')")
    @GetMapping("/list")
    public TableDataInfo list(DataInventoryRecord dataInventoryRecord) {
        startPage();
        List<DataInventoryRecord> list = dataInventoryRecordService.selectDataInventoryRecordList(dataInventoryRecord);
        return getDataTable(list);
    }

    /**
     * 导出库存记录列表
     */
    @PreAuthorize("@ss.hasPermi('data:inventoryRecord:export')")
    @Log(title = "库存记录", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, DataInventoryRecord dataInventoryRecord) {
        List<DataInventoryRecord> list = dataInventoryRecordService.selectDataInventoryRecordList(dataInventoryRecord);
        ExcelUtil<DataInventoryRecord> util = new ExcelUtil<DataInventoryRecord>(DataInventoryRecord.class);
        util.exportExcel(response, list, "库存记录数据");
    }

    /**
     * 获取库存记录详细信息
     */
    @PreAuthorize("@ss.hasPermi('data:inventoryRecord:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return AjaxResult.success(dataInventoryRecordService.selectDataInventoryRecordById(id));
    }

    /**
     * 新增库存记录
     */
    @PreAuthorize("@ss.hasPermi('data:inventoryRecord:add')")
    @Log(title = "库存记录", businessType = BusinessType.INSERT)
    @PostMapping
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult add(@RequestBody DataInventoryRecord dataInventoryRecord) {
        if (StringUtils.isNull(dataInventoryRecord.getUserId())) {
            return AjaxResult.error("请选择用户");
        } else {
            BaseGood good = goodService.selectBaseGoodById(dataInventoryRecord.getGoodId());
            BaseLimit limit = limitService.selectBaseLimitUse();
            SysUser user = userService.selectUserById(dataInventoryRecord.getUserId());
            DataInventory inventory = dataInventoryService.selectDataInventoryByUserIdAndGoodId(dataInventoryRecord.getUserId(), dataInventoryRecord.getGoodId());
            if (StringUtils.isNull(inventory)) {
                inventory = new DataInventory();
                inventory.setDeptId(dataInventoryRecord.getDeptId());
                inventory.setUserId(dataInventoryRecord.getUserId());
                inventory.setNickName(dataInventoryRecord.getNickName());
                inventory.setGoodId(dataInventoryRecord.getGoodId());
                inventory.setGoodCode(dataInventoryRecord.getGoodCode());
                inventory.setGoodName(dataInventoryRecord.getGoodName());
                inventory.setAmount(0);
                inventory.setCreateBy(getUsername());
                inventory.setCreateTime(DateUtils.getNowDate());
            }
            String strGold;
            if (dataInventoryRecord.getStockType().equals(SystemType.IN.getCode())) {
                strGold = "增加了" + dataInventoryRecord.getAmount() * good.getGoldBean() + "个金豆";
                user.setGoldAvailable(user.getGoldAvailable() + dataInventoryRecord.getAmount() * good.getGoldBean());
                user.setUserAvailable(user.getUserAvailable() + dataInventoryRecord.getAmount() * good.getGoldBean() / Integer.parseInt(limit.getGoldScale()));
                dataInventoryRecord.setInAmount(dataInventoryRecord.getAmount());
                dataInventoryRecord.setOutAmount(0);
                inventory.setAmount(inventory.getAmount() + dataInventoryRecord.getAmount());
            } else {
                strGold = "扣减了" + dataInventoryRecord.getAmount() * good.getGoldBean() + "个金豆";
                user.setGoldAvailable(user.getGoldAvailable() - dataInventoryRecord.getAmount() * good.getGoldBean());
                user.setUserAvailable(user.getUserAvailable() - dataInventoryRecord.getAmount() * good.getGoldBean() / Integer.parseInt(limit.getGoldScale()));
                dataInventoryRecord.setAmount(0 - dataInventoryRecord.getAmount());
                dataInventoryRecord.setOutAmount(dataInventoryRecord.getAmount());
                dataInventoryRecord.setInAmount(0);
                inventory.setAmount(inventory.getAmount() - dataInventoryRecord.getAmount());
            }
            int userAvailable = user.getGoldAvailable() / Integer.parseInt(limit.getGoldScale());
            user.setUserAvailable(userAvailable);
            userService.updateUserProfile(user);
            dataInventoryRecord.setBillNumber("系统调整库存");
            dataInventoryRecord.setStockDesc(StringUtils.format("系统调整库存。{}!", strGold));
            dataInventoryRecordService.insertDataInventoryRecord(dataInventoryRecord);
            if (StringUtils.isNull(inventory.getId())) {
                dataInventoryService.insertDataInventory(inventory);
            } else {
                inventory.setUpdateBy(getUsername());
                inventory.setUpdateTime(DateUtils.getNowDate());
                dataInventoryService.updateDataInventory(inventory);
            }
            return AjaxResult.success();
        }
    }

    /**
     * 修改库存记录
     */
    @PreAuthorize("@ss.hasPermi('data:inventoryRecord:edit')")
    @Log(title = "库存记录", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody DataInventoryRecord dataInventoryRecord) {
        return toAjax(dataInventoryRecordService.updateDataInventoryRecord(dataInventoryRecord));
    }

    /**
     * 删除库存记录
     */
    @PreAuthorize("@ss.hasPermi('data:inventoryRecord:remove')")
    @Log(title = "库存记录", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(dataInventoryRecordService.deleteDataInventoryRecordByIds(ids));
    }
}
